<template>
  <div class="test-wrapper">
    <div class="background-overlay"></div>

    <!-- 未开始提示页 -->
    <div v-if="!started" class="start-page">
      <h2 class="start-title">欢迎参与 MBTI 性格测试</h2>
      <p class="start-desc">一共 93 道题，预计耗时 8~10 分钟，测完后可查看测试结果</p>
      <el-button type="primary" size="large" round @click="startTest">开始测试</el-button>
    </div>

    <!-- 正在加载题目 -->
    <div v-else-if="loading" class="loading">
      <el-icon><i-ep-loading /></el-icon>
      <p>正在加载题目，请稍候...</p>
    </div>

    <!-- MBTI测试主界面 -->
    <div v-else-if="isLoggedIn && questions.length > 0" class="mbti-test-card">
      <h2 class="title">MBTI 性格测试</h2>

      <div class="question-count">
        第 {{ currentIndex + 1 }} 题 / 共 {{ questions.length }} 题
      </div>

      <div class="question-box">
        <div class="question-text">{{ currentQuestion.text }}</div>

        <el-radio-group v-model="answers[currentIndex]" class="options">
          <el-radio :label="'A'">{{ currentQuestion.a }}</el-radio>
          <el-radio :label="'B'">{{ currentQuestion.b }}</el-radio>
        </el-radio-group>

        <div class="buttons">
          <el-button :disabled="currentIndex === 0" @click="prevQuestion" round>上一题</el-button>

          <el-button
              v-if="currentIndex < questions.length - 1"
              type="primary"
              :disabled="!answers[currentIndex]"
              @click="nextQuestion"
              round
          >
            下一题
          </el-button>

          <el-button
              v-else
              type="success"
              :disabled="!answers[currentIndex]"
              @click="submitAnswers"
              round
          >
            提交并查看结果
          </el-button>
        </div>
      </div>
    </div>

    <!-- 未登录提示 -->
    <div v-else-if="!isLoggedIn" class="not-logged-in">
      <p>请先登录后再进行 MBTI 测试。</p>
      <el-button type="primary" @click="goLogin">前往登录</el-button>
    </div>

    <!-- 无题目提示 -->
    <div v-else class="no-questions">
      <p>未获取到题目，请稍后重试。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import "element-plus/es/components/message/style/css";

const started = ref(false);
const currentIndex = ref(0);
const questions = ref([]);
const answers = ref([]);
const isLoggedIn = ref(false);
const loading = ref(false);

const currentQuestion = computed(() => questions.value[currentIndex.value] || {});

// 初始化登录状态及清理历史测试数据
isLoggedIn.value = !!sessionStorage.getItem("loggedIn");
if (isLoggedIn.value) {
  // 每次登录进入测试页都清除之前测试状态，必须重新测试
  sessionStorage.removeItem("mbtiCompleted");
  sessionStorage.removeItem("mbtiResult");
}

const startTest = async () => {
  started.value = true;
  loading.value = true;

  if (!isLoggedIn.value) {
    loading.value = false;
    return;
  }

  try {
    const res = await axios.get("http://localhost:8081/api/mbti/questions");
    questions.value = res.data;
    answers.value = Array(res.data.length).fill(null);
  } catch (err) {
    console.error("加载失败：", err);
    ElMessage.error("题目加载失败，请稍后再试");
  } finally {
    loading.value = false;
  }
};

const nextQuestion = () => {
  if (currentIndex.value < questions.value.length - 1) currentIndex.value++;
};

const prevQuestion = () => {
  if (currentIndex.value > 0) currentIndex.value--;
};

const submitAnswers = async () => {
  // 统计MBTI分数
  const score = { E: 0, I: 0, S: 0, N: 0, T: 0, F: 0, J: 0, P: 0 };

  questions.value.forEach((q, i) => {
    const ans = answers.value[i];
    if (!ans) return;
    let type = q.direction;
    if (ans === "B") {
      const opposite = { E: "I", I: "E", S: "N", N: "S", T: "F", F: "T", J: "P", P: "J" };
      type = opposite[q.direction];
    }
    score[type]++;
  });

  const mbtiType =
      (score.E > score.I ? "E" : "I") +
      (score.S > score.N ? "S" : "N") +
      (score.T > score.F ? "T" : "F") +
      (score.J > score.P ? "J" : "P");

  const studentId = Number(sessionStorage.getItem("studentId"));
  const payload = {
    studentId,
    type: mbtiType,
    answers: answers.value.map((ans, i) => ({
      questionId: questions.value[i].id,
      answer: ans,
    })),
  };

  try {
    await axios.post("http://localhost:8081/api/mbti/submit", payload);
    await axios.post("http://localhost:8081/api/mbti/record", payload);

    // 标记测试完成并保存结果
    sessionStorage.setItem("mbtiResult", JSON.stringify({ type: mbtiType, answers: answers.value }));
    sessionStorage.setItem("mbtiCompleted", "true");

    ElMessage.success("测试完成，结果已提交，请点击“我的结果”查看");
  } catch (err) {
    console.error("提交失败：", err);
    ElMessage.error("提交失败，请稍后再试");
  }
};

const goLogin = () => {
  window.location.href = "/login";
};
</script>

<style scoped>
.test-wrapper {
  min-height: 100vh;
  background: linear-gradient(135deg, #e3f2fd, #fce4ec);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  position: relative;
  padding: 80px 20px 40px;
}

.background-overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  background:
      radial-gradient(circle at top left, rgba(255, 255, 255, 0.2), transparent 70%),
      radial-gradient(circle at bottom right, rgba(255, 255, 255, 0.2), transparent 70%);
  pointer-events: none;
  z-index: 0;
}

.start-page,
.mbti-test-card,
.loading,
.not-logged-in,
.no-questions {
  background: #fff;
  padding: 30px 40px;
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
  max-width: 600px;
  width: 100%;
  z-index: 1;
  text-align: center;
}

.start-title {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 10px;
}

.start-desc {
  font-size: 16px;
  color: #666;
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #333;
}

.question-count {
  font-size: 16px;
  margin-bottom: 15px;
  color: #555;
}

.question-box {
  margin-top: 20px;
}

.question-text {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
}

.options {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.buttons {
  display: flex;
  justify-content: space-between;
}

.loading p {
  font-size: 16px;
  margin-top: 10px;
}

.el-radio {
  margin: 0 20px;
}
</style>
